package top.shiyiri.servlet;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * @author Aunean
 * @date 2022/1/27 10:30
 */
public class HelloServlet implements Servlet {

    public HelloServlet() {
        System.out.println("构造器方法");
    }
    @Override
    public void init(ServletConfig servletConfig) throws ServletException {
        System.out.println("init初始化方法");

        //1.可以获取Servlet程序的别名servlet-name的值
        System.out.println("HelloServlet程序的别名是：" + servletConfig.getServletName());
        //2.获取初始化参数init-param
        System.out.println("初始化参数username的值是：" + servletConfig.getInitParameter("username"));
        System.out.println("初始化参数url的值是：" + servletConfig.getInitParameter("url"));
        //3.获取ServletContext对象
        System.out.println(servletConfig.getServletContext());
    }

    @Override
    public ServletConfig getServletConfig() {
        return null;
    }

    /**
     * service方法是专门用来处理请求和响应的
     * @param servletRequest
     * @param servletResponse
     * @throws ServletException
     * @throws IOException
     */
    @Override
    public void service(ServletRequest servletRequest, ServletResponse servletResponse) throws ServletException, IOException {
        //类型转换（HttpServletRequest中有getMethod()）
        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
        //System.out.println(httpServletRequest.getMethod());
        if (httpServletRequest.getMethod().equals("GET")) {
            System.out.println("Hello Servlet 被GET访问了");
        } else if ("POST".equalsIgnoreCase(httpServletRequest.getMethod())) {
            System.out.println("Hello Servlet 被POST访问了");
        }
    }

    @Override
    public String getServletInfo() {
        return null;
    }

    @Override
    public void destroy() {
        System.out.println("destroy销毁方法");
    }
}
